package nju.software.tagmanager.handler;

import nju.software.tagmanager.common.constant.MessageConstant;
import nju.software.tagmanager.common.exception.BaseException;
import nju.software.tagmanager.common.exception.TokenExpiredException;
import nju.software.tagmanager.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * @author: raychou
     * @params: [ex]
     * @paramTypes: [nju.software.tagmanager.exception.BaseException]
     * @return: nju.software.tagmanager.result.Result
     * @date: 2023/9/1 16:12
     * @description: 捕获业务异常
     *
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        if (ex instanceof TokenExpiredException) {
            return Result.error(50000, ex.getMessage());
        }

        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }


    /**
     * @author: raychou
     * @date: 2023/8/30 19:39
     * @description: 处理因为unique字段已存在相同记录导致的异常
     *
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        String message = ex.getMessage();
        log.error("异常信息：{}", message);
        if(message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            String username = split[2];
            String msg = username + MessageConstant.ALREADY_EXISTS;
            return Result.error(msg);
        }else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }

}
